using WeatherMcpServer.Tools;

var builder = WebApplication.CreateBuilder(args);

// 添加CORS支持
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 基础服务
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient();

// MCP服务配置
builder.Services
    .AddMcpServer()
    .WithHttpTransport()
    .WithToolsFromAssembly(typeof(Program).Assembly);

var app = builder.Build();

// 启用CORS
app.UseCors();

// 映射MCP端点
app.MapMcp();

// 添加一个显示所有路由的端点
app.MapGet("/routes", async context =>
{
    var endpoints = app.Services.GetService<IEnumerable<EndpointDataSource>>();
    var response = "Available endpoints:\n";

    foreach (var endpointSource in endpoints)
    {
        foreach (var endpoint in endpointSource.Endpoints)
        {
            if (endpoint is RouteEndpoint routeEndpoint)
            {
                response += $"{routeEndpoint.RoutePattern.RawText}\n";
            }
        }
    }

    await context.Response.WriteAsync(response);
});

// 健康检查端点
app.MapGet("/health", () => "Weather MCP Server is running!");

// 添加一个简单的测试端点，用于验证CORS
app.MapPost("/test", async context =>
{
    var requestBody = await context.Request.ReadFromJsonAsync<object>();
    await context.Response.WriteAsJsonAsync(new { 
        message = "Test endpoint working!", 
        received = requestBody,
        timestamp = DateTime.UtcNow
    });
});

// 添加一个简单的天气查询端点，用于测试
app.MapPost("/weather", async context =>
{
    try
    {
        var request = await context.Request.ReadFromJsonAsync<WeatherRequest>();
        if (request == null)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "Invalid request format" });
            return;
        }

        // 这里可以调用天气工具，但为了简化，直接返回测试数据
        var response = new
        {
            latitude = request.Latitude,
            longitude = request.Longitude,
            weather = "测试天气数据 - 晴天，25°C",
            timestamp = DateTime.UtcNow
        };

        await context.Response.WriteAsJsonAsync(response);
    }
    catch (Exception ex)
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = ex.Message });
    }
});

app.Run();

// 请求模型
public class WeatherRequest
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}